package com.lw.leetcode.stack.b;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * 1963. 使字符串平衡的最小交换次数
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/18 12:25
 */
public class MinSwaps {


    public static void main(String[] args) {
        MinSwaps test = new MinSwaps();
        String str = "][[]][][[][]";
        int i = test.minSwaps(str);
        System.out.println(i);
    }

    public int minSwaps2(String s) {
        Stack<Character> stack = new Stack<>();
        char[] arr = s.toCharArray();
        for (char c : arr) {
            if (c == '[') {
                stack.add(c);
            } else {
                if (stack.isEmpty() || stack.peek() == ']') {
                    stack.add(c);
                } else {
                    stack.pop();
                }
            }
        }
        return ((stack.size() >> 1) + 1) >> 1;
    }


    public int minSwaps(String s) {
        int a = 0;
        int b = 0;
        for (char c : s.toCharArray()) {
            if (c == '[') {
                a++;
            } else {
                if (a > 0) {
                    a--;
                } else {
                    b++;
                }
            }
        }
        return (((a + b) >> 1) + 1) >> 1;
    }

}
